package com.cogent.dynamicform.form.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.cogent.common.util.MapUtil;
import com.cogent.dynamicform.cache.EnumCacheManager;
import com.cogent.dynamicform.domain.BaseFormColumnDomain;
import com.cogent.dynamicform.domain.FormColumnDomain;
import com.cogent.dynamicform.form.AbstractDynamicForm;

public class MutiSelectDynamicFormImpl extends AbstractDynamicForm {
	public String genQueryField(BaseFormColumnDomain formColumnDomain, HashMap formMap) {
		return "";
	}
	
	public String genInputField(FormColumnDomain formColumnDomain, HashMap formMap) {
		if(formColumnDomain.getViewmodel() > 0)
			return getShowValue(formColumnDomain, formMap) + "&nbsp;";
		StringBuffer str = new StringBuffer();
		List enmuList = (List)EnumCacheManager.get( formColumnDomain.getTypecode() + "!LIST");
		Iterator it = enmuList.iterator();
		int num = 1;
		String curvalue = MapUtil.getStringValue(formMap, formColumnDomain.getName());
		while(it.hasNext()) {
			HashMap map = (HashMap)it.next();
			String val = MapUtil.getStringValue(map, "value");
			str.append("<input type=\"checkbox\" name=\"").append(formColumnDomain.getName())
				.append("\" id=\"").append(formColumnDomain.getName()).append(num++)
				.append("\" value=\"").append(val).append("\"");
			if(curvalue.indexOf("," + val + ",") >= 0)
				str.append(" checked");
			str.append("/>").append(MapUtil.getStringValue(map, "enumitemname")).append("&nbsp;");
				
		}
		
		return str.toString();
	}	
	
	public String getShowValue(BaseFormColumnDomain formColumnDomain, HashMap formMap) {
		if(formColumnDomain.getShowtype() == 1)
			return "&nbsp;";
		StringBuffer str = new StringBuffer();
		List enmuList = (List)EnumCacheManager.get( formColumnDomain.getTypecode() + "!LIST");
		Iterator it = enmuList.iterator();
		String name = formColumnDomain.getName();
		if(name.indexOf(".") > 0)
			name = name.substring(name.indexOf(".") + 1);
		String curvalue = MapUtil.getStringValue(formMap, name);
		while(it.hasNext()) {
			HashMap map = (HashMap)it.next();
			String val = MapUtil.getStringValue(map, "value");
			if(curvalue.indexOf("," + val + ",") >= 0)
				str.append(MapUtil.getStringValue(map, "enumitemname")).append(",");
		}
		String ret = str.toString();
		if(ret.length()>0)
			ret = ret.substring(0, ret.length()-1);
		else
			ret = "&nbsp;";
		
		return ret;
	}
	
	public void dealFormValue(FormColumnDomain formColumnDomain, HashMap formMap) {
		String curvalue = "," + MapUtil.getStringValue(formMap, formColumnDomain.getName()) + ",";
		formMap.put(formColumnDomain.getName(), curvalue);
	}
}